{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "98d09cd6-5bc6-4813-a99c-bab2445c0fe2",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "F:\\programData\\conda\\env\\ChatGLM2-6B\\lib\\site-packages\\numpy\\_distributor_init.py:30: UserWarning: loaded more than 1 DLL from .libs:\n",
      "F:\\programData\\conda\\env\\ChatGLM2-6B\\lib\\site-packages\\numpy\\.libs\\libopenblas.FB5AE2TYXYH2IJRDKGDGQ3XBKLKTF43H.gfortran-win_amd64.dll\n",
      "F:\\programData\\conda\\env\\ChatGLM2-6B\\lib\\site-packages\\numpy\\.libs\\libopenblas64__v0.3.23-246-g3d31191b-gcc_10_3_0.dll\n",
      "  warnings.warn(\"loaded more than 1 DLL from .libs:\"\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import torch\n",
    "from torch.utils import data\n",
    "from d2l import torch as d2l\n",
    "\n",
    "true_w = torch.tensor([2,-3.4])\n",
    "true_b = 4.2\n",
    "features,labels = d2l.synthetic_data(true_w,true_b,10000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "caf00a3f-8f58-4c89-93b9-0aef0245d2b1",
   "metadata": {},
   "outputs": [],
   "source": [
    "def load_array(data_arrays,batch_size,is_train=True):\n",
    "    dataset = data.TensorDataset(*data_arrays)\n",
    "    return data.DataLoader(dataset,batch_size,shuffle=is_train)\n",
    "\n",
    "batch_size = 10\n",
    "data_iter = load_array((features,labels),batch_size)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "19334602-7e1a-4d3f-8d40-72ab04d695b8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[tensor([[-1.0693, -0.0296],\n",
       "         [-0.4388, -1.7772],\n",
       "         [-2.0911, -0.1310],\n",
       "         [-1.2071,  0.8025],\n",
       "         [-0.2812, -0.2779],\n",
       "         [ 0.3680,  0.8238],\n",
       "         [ 0.2345,  0.3344],\n",
       "         [ 0.9554,  0.0923],\n",
       "         [ 0.5468, -0.0661],\n",
       "         [-0.8354,  0.4530]]),\n",
       " tensor([[ 2.1488],\n",
       "         [ 9.3664],\n",
       "         [ 0.4458],\n",
       "         [-0.9503],\n",
       "         [ 4.5747],\n",
       "         [ 2.1432],\n",
       "         [ 3.5236],\n",
       "         [ 5.8102],\n",
       "         [ 5.5133],\n",
       "         [ 0.9927]])]"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "next(iter(data_iter))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "75764354-1429-4c87-bf19-e6e25fe83ade",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义模型\n",
    "from torch import nn\n",
    "net = nn.Sequential(nn.Linear(2,1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "99e24961-0a56-435b-96c8-a7bc094c657d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([0.])"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 初始化模型参数\n",
    "net[0].weight.data.normal_(0,0.01)\n",
    "net[0].bias.data.fill_(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "5b23fe4c-317d-417d-ac64-6ca169209d37",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义损失函数\n",
    "loss = nn.MSELoss()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "d2f1784e-52cf-4f5c-b53e-2346a23bda52",
   "metadata": {},
   "outputs": [],
   "source": [
    "trainer = torch.optim.SGD(net.parameters(),lr=0.03)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "67ec8e01-d0fe-4caf-96cf-c01e8a9cb3e6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1,loss 0.000101\n",
      "epoch 2,loss 0.000102\n",
      "epoch 3,loss 0.000101\n",
      "epoch 4,loss 0.000102\n",
      "epoch 5,loss 0.000102\n",
      "epoch 6,loss 0.000102\n",
      "epoch 7,loss 0.000103\n",
      "epoch 8,loss 0.000101\n",
      "epoch 9,loss 0.000102\n",
      "epoch 10,loss 0.000102\n",
      "epoch 11,loss 0.000102\n",
      "epoch 12,loss 0.000101\n",
      "epoch 13,loss 0.000102\n",
      "epoch 14,loss 0.000102\n",
      "epoch 15,loss 0.000103\n",
      "epoch 16,loss 0.000101\n",
      "epoch 17,loss 0.000101\n",
      "epoch 18,loss 0.000102\n",
      "epoch 19,loss 0.000101\n",
      "epoch 20,loss 0.000102\n",
      "epoch 21,loss 0.000101\n",
      "epoch 22,loss 0.000102\n",
      "epoch 23,loss 0.000102\n",
      "epoch 24,loss 0.000101\n",
      "epoch 25,loss 0.000102\n",
      "epoch 26,loss 0.000101\n",
      "epoch 27,loss 0.000103\n",
      "epoch 28,loss 0.000101\n",
      "epoch 29,loss 0.000102\n",
      "epoch 30,loss 0.000102\n",
      "epoch 31,loss 0.000104\n",
      "epoch 32,loss 0.000101\n",
      "epoch 33,loss 0.000102\n",
      "epoch 34,loss 0.000102\n",
      "epoch 35,loss 0.000103\n",
      "epoch 36,loss 0.000101\n",
      "epoch 37,loss 0.000101\n",
      "epoch 38,loss 0.000101\n",
      "epoch 39,loss 0.000101\n",
      "epoch 40,loss 0.000105\n",
      "epoch 41,loss 0.000102\n",
      "epoch 42,loss 0.000102\n",
      "epoch 43,loss 0.000102\n"
     ]
    }
   ],
   "source": [
    "# 训练\n",
    "num_epochs = 43\n",
    "for epoch in range(num_epochs):\n",
    "    for x,y in data_iter:\n",
    "        l = loss(net(x),y)\n",
    "        trainer.zero_grad()\n",
    "        l.backward()\n",
    "        trainer.step()\n",
    "    l = loss(net(features),labels)\n",
    "    print(f\"epoch {epoch +1},loss {l:f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "fdbef078-9d35-4051-9ab0-0d6824db67a2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "w的估计误差： tensor([-0.0007,  0.0003])\n",
      "b的估计误差： tensor([0.0004])\n"
     ]
    }
   ],
   "source": [
    "w = net[0].weight.data\n",
    "print(\"w的估计误差：\",true_w - w.reshape(true_w.shape))\n",
    "b = net[0].bias.data\n",
    "print(\"b的估计误差：\",true_b - b)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.17"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
